import * as Router from 'koa-router';
import dingTalkApi from 'dingtalk-app/dtalk/DingTalkApi';
import approvalService from '../services/approvalService';
import dTalkApi from '../core/dTalkApi';
import dTalkApiUtil from 'dingtalk-app/dtalk/dTalkApiUtil';
import { IRouterContext } from 'koa-router';

//审批
let router = new Router();
router.prefix('/api/approval');
//该接口是向审批人显示其所属所有员工的临时计划待审核列表与申请取消的计划列表(临时计划  待审核)
router.post('/listMonthPlanToLeader', async (ctx: IRouterContext, next: any) => {
    let user: any = dingTalkApi.decode(ctx.header.authorization);
    let rq: any = ctx.request
    let res = rq.body;
    let monthplanData:any = []
    let access_token=await dTalkApiUtil.getAccessToken();
    if(user!=null&&!(user==undefined)&&user !=''){
        monthplanData = await approvalService.listMonthPlanByMonth(user, res.month,access_token);
    }else{
        user=await dTalkApi.getUserDetail(res.userid,access_token)
        monthplanData = await approvalService.listMonthPlanByMonth(user, res.month,access_token);
    }
    if (monthplanData.length != 0) {
        ctx.body = monthplanData;
        ctx.status = 200;
    } else {
        ctx.body = [];
    }
    await next()
});

//改接口是上级领导审批后,结果获取并保存的接口  批量审批也可以单个审批
//参数:result:审批结果(同意通过|不同意|驳回修改)  idList:审批记录的_id列表(数组),month:月份 leaderId:审批人id
router.post('/leaderApprovalResult', async (ctx: IRouterContext, next: any) => {
    let user: any = dingTalkApi.decode(ctx.header.authorization);
    let rq: any = ctx.request;
    let res = rq.body;//res包含审批人的userid,month:几月份的月计划
    let access_token=await dTalkApiUtil.getAccessToken();
    await approvalService.saveApprovalResult(res.idList, res.result, res.month, res.leaderId);
    let monthplanData = await approvalService.listMonthPlanByMonth(user, res.month,access_token);
    if (monthplanData.length != 0) {
        ctx.body = monthplanData;
        ctx.status = 200;
    } else {
        ctx.body = [];
    }
    await next()
});

export default router